from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile, Department, LeaveApplication, LeaveType


class CustomUserCreationForm(UserCreationForm):
    """自定义用户注册表单"""
    first_name = forms.CharField(label='姓名', max_length=30, required=True)
    last_name = forms.CharField(label='姓氏', max_length=30, required=False)
    email = forms.EmailField(label='邮箱', required=True)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置中文标签
        self.fields['username'].label = '用户名'
        self.fields['password1'].label = '密码'
        self.fields['password2'].label = '确认密码'


class UserProfileForm(forms.ModelForm):
    """用户配置表单"""

    class Meta:
        model = UserProfile
        fields = ['employee_id', 'department', 'position', 'phone', 'hire_date']
        widgets = {
            'hire_date': forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),

        }
        labels = {
            'employee_id': '工号',
            'department': '部门',
            'position': '职位',
            'phone': '电话',
            'hire_date': '入职日期',
        }


class UserUpdateForm(forms.ModelForm):
    """用户信息更新表单"""

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
        labels = {
            'first_name': '姓名',
            'last_name': '姓氏',
            'email': '邮箱',
        }


class LeaveApplicationForm(forms.ModelForm):
    """请假申请表单"""

    class Meta:
        model = LeaveApplication
        fields = [
            'leave_type', 'start_date', 'end_date', 'reason',
            'attachment', 'emergency_contact', 'emergency_phone', 'work_handover'
        ]
        widgets = {
            'start_date': forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),
            'end_date': forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),
            'reason': forms.Textarea(attrs={'rows': 4}),
            'work_handover': forms.Textarea(attrs={'rows': 3}),
        }
        labels = {
            'leave_type': '请假类型',
            'start_date': '开始日期',
            'end_date': '结束日期',
            'reason': '请假原因',
            'attachment': '附件',
            'emergency_contact': '紧急联系人',
            'emergency_phone': '紧急联系电话',
            'work_handover': '工作交接安排',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 只显示启用的请假类型
        self.fields['leave_type'].queryset = LeaveType.objects.filter(is_active=True)

        # 设置必填字段的样式
        for field_name in ['leave_type', 'start_date', 'end_date', 'reason']:
            self.fields[field_name].required = True

    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        leave_type = cleaned_data.get('leave_type')

        if start_date and end_date:
            if start_date > end_date:
                raise forms.ValidationError('开始日期不能晚于结束日期')

            # 计算请假天数
            from .utils import WorkdayCalculator
            days = WorkdayCalculator.calculate_workdays(start_date, end_date)

            if leave_type and days > leave_type.max_days:
                raise forms.ValidationError(f'请假天数不能超过{leave_type.max_days}天')

        return cleaned_data


class LeaveFilterForm(forms.Form):
    """请假筛选表单"""
    STATUS_CHOICES = [
        ('', '全部状态'),
        ('draft', '草稿'),
        ('submitted', '已提交'),
        ('supervisor_approved', '主管已批准'),
        ('approved', '已批准'),
        ('rejected', '已拒绝'),
        ('cancelled', '已取消'),
    ]

    status = forms.ChoiceField(choices=STATUS_CHOICES, required=False, label='状态')
    leave_type = forms.ModelChoiceField(
        queryset=LeaveType.objects.filter(is_active=True),
        required=False,
        empty_label='全部类型',
        label='请假类型'
    )
    start_date = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'),
        label='开始日期',

    )
    end_date = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={'type': 'date'}),
        label='结束日期'
    )


class UserRoleForm(forms.ModelForm):
    """用户角色分配表单"""

    class Meta:
        model = UserProfile
        fields = ['role', 'department', 'supervisor', 'annual_leave_days']
        labels = {
            'role': '用户角色',
            'department': '部门',
            'supervisor': '直属上级',
            'annual_leave_days': '年假天数',
        }
        help_texts = {
            'role': '选择用户的系统角色，决定其权限范围',
            'supervisor': '选择该用户的直属上级（用于审批流程）',
            'annual_leave_days': '该用户每年可用的年假天数',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 只显示可以作为上级的用户（主管、HR、管理员）
        self.fields['supervisor'].queryset = UserProfile.objects.filter(
            role__in=['supervisor', 'hr', 'admin']
        ).exclude(id=self.instance.id if self.instance else None)

        # 设置角色选择的样式
        self.fields['role'].widget.attrs.update({'class': 'form-control'})
        self.fields['department'].widget.attrs.update({'class': 'form-control'})
        self.fields['supervisor'].widget.attrs.update({'class': 'form-control'})
        self.fields['annual_leave_days'].widget.attrs.update({'class': 'form-control', 'min': '0', 'max': '30'})


class UserSearchForm(forms.Form):
    """用户搜索表单"""
    ROLE_CHOICES = [
        ('', '全部角色'),
        ('employee', '员工'),
        ('supervisor', '主管'),
        ('hr', '人事'),
        ('admin', '管理员'),
    ]

    search = forms.CharField(
        max_length=100,
        required=False,
        label='搜索',
        widget=forms.TextInput(attrs={
            'placeholder': '搜索用户名、姓名或工号...',
            'class': 'form-control'
        })
    )
    role = forms.ChoiceField(
        choices=ROLE_CHOICES,
        required=False,
        label='角色',
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    department = forms.ModelChoiceField(
        queryset=Department.objects.all(),
        required=False,
        empty_label='全部部门',
        label='部门',
        widget=forms.Select(attrs={'class': 'form-control'})
    )
